from app import db
from datetime import datetime

class SyncLog(db.Model):
    """同步日志模型"""
    __tablename__ = 'sync_logs'
    
    id = db.Column(db.Integer, primary_key=True)
    task_id = db.Column(db.Integer, db.ForeignKey('sync_tasks.id'), nullable=False)
    start_time = db.Column(db.DateTime, default=datetime.now)
    end_time = db.Column(db.DateTime)
    status = db.Column(db.String(20), default='running')  # running, success, failed
    total_records = db.Column(db.Integer, default=0)
    success_records = db.Column(db.Integer, default=0)
    failed_records = db.Column(db.Integer, default=0)
    error_message = db.Column(db.Text)
    
    def __repr__(self):
        return f'<SyncLog {self.id}>'
    
    def to_dict(self):
        return {
            'id': self.id,
            'task_id': self.task_id,
            'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'end_time': self.end_time.strftime('%Y-%m-%d %H:%M:%S') if self.end_time else None,
            'status': self.status,
            'total_records': self.total_records,
            'success_records': self.success_records,
            'failed_records': self.failed_records,
            'error_message': self.error_message,
            'duration': (self.end_time - self.start_time).total_seconds() if self.end_time else None
        }

class SyncLogDetail(db.Model):
    """同步日志详情模型"""
    __tablename__ = 'sync_log_details'
    
    id = db.Column(db.Integer, primary_key=True)
    log_id = db.Column(db.Integer, db.ForeignKey('sync_logs.id'), nullable=False)
    record_id = db.Column(db.String(100))  # 同步的记录ID
    status = db.Column(db.String(20))  # success, failed
    error_message = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.now)
    
    def __repr__(self):
        return f'<SyncLogDetail {self.id}>'